package com.example.research.controller;

import com.example.research.dto.ApiResponse;
import com.example.research.dto.AuditRequest;
import com.example.research.dto.PendingAuditItem;
import com.example.research.dto.AuditHistoryItem;
import com.example.research.entity.AuditRecord;
import com.example.research.service.AuditService;
import com.example.research.service.AuthService;
import com.example.research.utils.PermissionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 审核控制器
 */
@RestController
@RequestMapping("/audits")
@Validated
public class AuditController {

    @Autowired
    private AuditService auditService;

    @Autowired
    private AuthService authService;

    @Autowired
    private PermissionUtils permissionUtils;

    /**
     * 获取当前用户ID
     */
    private Long getCurrentUserId(String authHeader) {
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            throw new RuntimeException("未提供有效的认证信息");
        }
        String token = authHeader.substring(7);
        return authService.getUserIdFromToken(token);
    }

    /**
     * 查询所有审核记录
     */
    @GetMapping
    public ApiResponse<List<AuditRecord>> getAllAuditRecords() {
        try {
            List<AuditRecord> records = auditService.findAll();
            return ApiResponse.success(records);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 根据ID查询审核记录
     */
    @GetMapping("/{id}")
    public ApiResponse<AuditRecord> getAuditRecordById(@PathVariable Long id) {
        try {
            AuditRecord record = auditService.findById(id);
            if (record == null) {
                return ApiResponse.notFound("审核记录不存在");
            }
            return ApiResponse.success(record);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 查询当前用户的审核记录
     */
    @GetMapping("/my")
    public ApiResponse<List<AuditRecord>> getMyAuditRecords(@RequestHeader("Authorization") String authHeader) {
        try {
            Long userId = getCurrentUserId(authHeader);
            List<AuditRecord> records = auditService.findByAuditorId(userId);
            return ApiResponse.success(records);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 根据审核状态查询审核记录
     */
    @GetMapping("/status/{status}")
    public ApiResponse<List<AuditRecord>> getAuditRecordsByStatus(@PathVariable Integer status) {
        try {
            List<AuditRecord> records = auditService.findByAuditStatus(status);
            return ApiResponse.success(records);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 获取待审核的项目列表
     */
    @GetMapping("/pending")
    public ApiResponse<List<PendingAuditItem>> getPendingAuditItems(
            @RequestParam(required = false) Integer page,
            @RequestParam(required = false) Integer size,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String type,
            @RequestParam(required = false) String title,
            @RequestParam(required = false) String submitter) {
        try {
            List<PendingAuditItem> items = auditService.getPendingAuditItems();
            return ApiResponse.success(items);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 获取所有审核历史记录（用于审核历史页面）
     */
    @GetMapping("/history")
    public ApiResponse<List<AuditHistoryItem>> getAllAuditHistory(
            @RequestParam(required = false) Integer page,
            @RequestParam(required = false) Integer size,
            @RequestParam(required = false) String type,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String title,
            @RequestParam(required = false) String submitter,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        try {
            List<AuditHistoryItem> items = auditService.getAuditHistoryItems();
            return ApiResponse.success(items);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 根据成果类型和成果ID查询审核历史
     */
    @GetMapping("/history/{achievementType}/{achievementId}")
    public ApiResponse<List<AuditRecord>> getAuditHistoryByAchievement(
            @PathVariable Integer achievementType,
            @PathVariable Long achievementId) {
        try {
            List<AuditRecord> records = auditService.getAuditHistory(achievementType, achievementId);
            return ApiResponse.success(records);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 提交审核
     */
    @PostMapping("/submit")
    public ApiResponse<String> submitAudit(@Valid @RequestBody AuditRequest auditRequest,
                                         @RequestHeader("Authorization") String authHeader) {
        try {
            Long auditorId = getCurrentUserId(authHeader);
            auditService.submitForAudit(auditRequest, auditorId);
            return ApiResponse.success("审核提交成功");
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 审核通过
     */
    @PostMapping("/approve")
    public ApiResponse<String> approve(@RequestParam Integer achievementType,
                                     @RequestParam Long achievementId,
                                     @RequestParam(required = false) String comment,
                                     @RequestHeader("Authorization") String authHeader) {
        try {
            Long auditorId = getCurrentUserId(authHeader);
            auditService.approve(achievementType, achievementId, comment, auditorId);
            return ApiResponse.success("审核通过");
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 审核拒绝
     */
    @PostMapping("/reject")
    public ApiResponse<String> reject(@RequestParam Integer achievementType,
                                    @RequestParam Long achievementId,
                                    @RequestParam String comment,
                                    @RequestHeader("Authorization") String authHeader) {
        try {
            Long auditorId = getCurrentUserId(authHeader);
            auditService.reject(achievementType, achievementId, comment, auditorId);
            return ApiResponse.success("审核拒绝");
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
}
